

package com.platform.api.security;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.api.bzproject.model.BzTalent;
import com.platform.api.bzproject.service.IBzTalentService;
import com.platform.common.util.Json;
import com.platform.security.exception.ServerException;
import com.platform.security.service.AuthUserDetailsService;
import com.platform.security.service.UserConnect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 账号密码登录
 */
@Component
public class WebLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private final AuthUserDetailsService authUserDetailsService;

    private final WxMaService wxMaService;

    @Autowired
    private IBzTalentService iBzTalentService;



    @Autowired
    public WebLoginAuthenticationFilter(AuthUserDetailsService authUserDetailsService, WxMaService wxMaService) {
        super("/webLogin");
        this.authUserDetailsService = authUserDetailsService;
        this.wxMaService = wxMaService;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        System.out.println(request.getMethod());
        if (!ServletUtil.METHOD_POST.equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String requestBody = getStringFromStream(request);

        if (StrUtil.isBlank(requestBody)) {
            throw new ServerException("无法获取输入信息");
        }
        WebAuthenticationToken authentication = Json.parseObject(requestBody, WebAuthenticationToken.class);

        //手机、邮箱、密码
        String phone = String.valueOf(authentication.getPrincipal());
        String password = String.valueOf(authentication.getCredentials());

        UserConnect loadedUser = null;
        loadedUser = authUserDetailsService.loadUserByUserPhoneAndPassWord(phone,password);
        if (!loadedUser.isEnabled()) {
            throw new ServerException("账号不可用");
        }

        BzTalent talent = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("phone", phone));
        if(null != talent){
            if(talent.getStatus() == 1){
                throw new ServerException("账号审核中");
            }
            if(talent.getStatus() == 3){
                throw new ServerException("账号审核不通过,请联系平台");
            }
            if(talent.getStatus() == 4){
                throw new ServerException("账号已禁用,请联系平台");
            }
        }

        WebAuthenticationToken result = new WebAuthenticationToken(loadedUser, authentication.getCredentials());
        result.setDetails(authentication.getDetails());
        return result;
    }


    private String getStringFromStream(HttpServletRequest req) {
        ServletInputStream is;
        try {
            is = req.getInputStream();
            int nRead = 1;
            int nTotalRead = 0;
            byte[] bytes = new byte[10240];
            while (nRead > 0) {
                nRead = is.read(bytes, nTotalRead, bytes.length - nTotalRead);
                if (nRead > 0) {
                    nTotalRead = nTotalRead + nRead;
                }
            }
            return new String(bytes, 0, nTotalRead, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    @Autowired
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

    @Override
    @Autowired
    public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
        super.setAuthenticationSuccessHandler(successHandler);
    }

    @Override
    @Autowired
    public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
        super.setAuthenticationFailureHandler(failureHandler);
    }
}
